package util

import (
	"errors"
	"math/rand"
	"strconv"
	"time"
)

func Lock(key string, call func()) (bool, error) {
	key = "lock:" + key
	redisInstance := GetRedis()
	rand.Seed(time.Now().UnixNano())
	unique := key + ":" + strconv.Itoa(int(rand.Int63()))
	result, err := redisInstance.SetNX(key, unique, time.Second*2).Result()
	if err != nil {
		return false, err
	}
	if !result {
		return false, errors.New("操作频繁")
	}
	defer func() {
		data, _ := redisInstance.Get(key).Result()
		if data == unique {
			redisInstance.Del(key).Result()
		}
	}()
	call()
	return true, nil
}
